package com.FH.organization.department;

import com.FH.organization.people.KamMemberDAO;
import com.FH.util.AccessDB;
import com.FH.util.Pinyin4jUtil;
import com.FH.util.ResultDTO;
import com.FH.util.warnSrc;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by ygg on 2016/6/28.
 *
 * 部门接口实现累
 *
 */

@Stateless
public class DepartmentDAOImpl extends AccessDB implements DepartmentDAO{

    @EJB
    private KamMemberDAO kamMemberDAO;




    /**
     * 获取部门信息
     * @param search
     * @param page
     * @param size
     * @return
     * 如果需要查询部门下的用户，请在search中传入isNeedUser参数
     */
    @Override
    public ResultDTO getDepartmentInfo(String search,String page,String size) {

        ResultDTO resultDTO = new ResultDTO();

        try {
            JSONObject json = new JSONObject(search);
            String existName = "0";

            String sqlexit = "select count(1) from organization  where 1=1 ";

            String sql_w ="";//查询条件sql组合

            String sql_page = "";//分页sql组合
            Integer page_ok = Integer.parseInt(page);
            Integer size_ok = Integer.parseInt(page);
            if(page.equals("1")){
                sql_page = " limit 0,"+size+"";
            }else{
                sql_page = " limit "+((page_ok-1)*size_ok+1)+","+size+"";
            }

            if(json.has("organization_id")){
//                sql_w += " AND organization_id = "+json.getString("organization_id");
                sql_w += " AND organization_id ='" + json.getString("organization_id") + "'";
            }
            if(json.has("organization_name")){
                sql_w += " AND organization_name = '"+json.getString("organization_name") +"'";
            }
            if(json.has("parent_organization_id")){
                sql_w += " AND parent_organization_id = '"+json.getString("parent_organization_id") +"'";
            }
            if(json.has("base_org_id")){
                sql_w += " AND base_org_id = "+json.getString("base_org_id");
            }
            String sql_ok = sqlexit+sql_w ;//组合好的sql语句
            existName = getReportingToOne(sql_ok);//查询此数据是否存在

            List<String []> seresult = new ArrayList<String []>();

            List<DepartmentShowDTO> result = new ArrayList<DepartmentShowDTO>();

            if(!existName.equals("0")){
                String sql ="SELECT organization_id,organization_name,parent_organization_id,organization_code,organization_state,is_leaf_,create_time_,creater_id,sort_no,status,base_org_id,PARENT_ORG_ID" +
                        " FROM organization WHERE 1=1 "+sql_w + " ORDER BY base_org_id ASC" + sql_page;
                seresult = this.getReportingTo(sql);

                //构建返回对象
                for (int i = 0; i < seresult.size(); i++){

                    DepartmentShowDTO department = new DepartmentShowDTO();
                    department.setOrganization_id(seresult.get(i)[1]);
                    department.setOrganization_name(seresult.get(i)[2]);
                    department.setParent_organization_id(seresult.get(i)[3]);
                    department.setOrganization_code(Pinyin4jUtil.converterToFirstSpell(seresult.get(i)[2]).toUpperCase());
                    department.setOrganization_state(seresult.get(i)[5]);
                    department.setIs_leaf(seresult.get(i)[6]);
                    department.setCreate_time(seresult.get(i)[7]);
                    department.setCreater_id(seresult.get(i)[8]);
                    department.setSort_no(seresult.get(i)[9]);
                    department.setStatus(seresult.get(i)[10]);
                    department.setBase_org_id(seresult.get(i)[11]);
                    department.setPARENT_ORG_ID(seresult.get(i)[12]);
                    if(seresult.get(i)[12]!=null&&seresult.get(i)[12]!=""){
                        String sqlnumber="SELECT COUNT(0) FROM organization WHERE PARENT_ORG_ID='"+seresult.get(i)[12]+ "'";
                        String childTotal = getReportingToOne(sqlnumber);//查询此数据是否存在
                        department.setChildTotal(childTotal);
                    }
                    if(json.has("isNeedUser")){
                        //获取该部门下的人员列表
                        String organization_id = seresult.get(i)[1];
                        ResultDTO userList ;
                        userList =kamMemberDAO.getUserListInfo("{organization_id:"+organization_id+"}","0","9999999");
                        department.setUser(userList.getValues());
                    }

                    result.add(department);

                }
            }


            if(seresult.size()!=0) {
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.get_success);
            }else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
            }

            resultDTO.setValues(result);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return resultDTO;

    }

    /**
     * 添加部门
     * @param departmentPullDTO
     * @return
     */
    @Override
    public ResultDTO addDepartmentInfo(DepartmentPullDTO departmentPullDTO) {

        String sql_isHas = "select count(1) from organization WHERE organization_name='"+departmentPullDTO.getOrganization_name()+"'";

        String existOrganization = getReportingToOne(sql_isHas);//插入前，查询是否有重复字段

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//日期格式化

        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        int resultls = 0;

        //构建返回对象
        ResultDTO resultDTO = new ResultDTO();

        if(existOrganization.equals("0")){

            String organization_insert = "";

            //构建插入sql
            organization_insert +="INSERT  INTO organization(organization_id,organization_name,parent_organization_id,organization_code,organization_state,is_leaf_,create_time_,creater_id,sort_no,STATUS) "+
                                "VALUES('"+uuid+"','"+departmentPullDTO.getOrganization_name()+ "','" +departmentPullDTO.getParent_organization_id()+"','"
                                    +departmentPullDTO.getOrganization_code()+"','" +departmentPullDTO.getOrganization_state()+ "','"+departmentPullDTO.getIs_leaf()+"','"+df.format(new Date())+"','"
                                    +departmentPullDTO.getCreater_id()+"','" +departmentPullDTO.getSort_no()+"','" +departmentPullDTO.getStatus()+"')";
            //插入业务表
            resultls =  addReportingTo(organization_insert);

        }
        if(resultls!=0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.add_success);
        }else{
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
        }

        return resultDTO;
    }

    @Override
    public ResultDTO updateDepartmentInfo(DepartmentPullDTO departmentPullDTO) {
        return null;
    }

    @Override
    public ResultDTO deleteDepartmentInfo(DepartmentPullDTO departmentPullDTO) {
        //删除之前查询一下该表是否有记录
        String sql = "select count(1) from organization where organization_id='" + departmentPullDTO.getOrganization_id() + "'";

        String existName = getReportingToOne(sql);

        int result = 0;

        if (!existName .equals(0)) {

            String QUERY = "";
            QUERY += "delete from organization where organization_id='" + departmentPullDTO.getOrganization_id() + "'";

            result = this.addReportingTo(QUERY);
        }

        ResultDTO resultDTO = new ResultDTO();
        if (result != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.delete_success);

        }
        else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.delete_fail);
        }
        return resultDTO;
    }

}
